﻿using Sustainalytics.Synchronization.Interface;
using System;

namespace Sustainalytics.ClientDW.Synchronization.RiskRatingsBenchmarks
{
    public class RiskRatingsBenchmarksSyncStep : ISyncStep
    {
        private SyncContext _syncContext;

        public SyncStepOrder ExecutionOrder => SyncStepOrder.SyncRiskRatingsBenchmarks;

        public SyncContext Start(SyncContext syncContext)
        {
            _syncContext = syncContext;

            try
            {
                var container = SimpleInjectorConfig.Register(new SyncContextLogger(syncContext), syncContext.GAConnectionStrings);
                _syncContext.Token.ThrowIfCancellationRequested();

                container.GetInstance<RiskRatingsBenchmarkSync>().Start(syncContext);

                _syncContext.Token.ThrowIfCancellationRequested();

                container.GetInstance<RiskRatingsHistoricalDataSync>().Start(syncContext.Token);

                _syncContext.Status = SyncOperationStatus.Succeeded;
            }
            catch (AggregateException ex)
            {
                _syncContext.Log(ex.Flatten().ToString());
                _syncContext.Status = SyncOperationStatus.Failed;
                throw;
            }
            catch (Exception ex)
            {
                _syncContext.Log(ex.ToString());
                _syncContext.Status = SyncOperationStatus.Failed;
                throw;
            }

            return _syncContext;
        }
    }
}
